package com.xiqing.wechat.web.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by xuw on 16/11/13.
 */
public class JsApiSign {
    /**日志*/
    private static final Logger  logger= LoggerFactory.getLogger (JsApiSign.class);


    static String create_nonce_str() {

        return UUID.randomUUID().toString();
    }

    public static String create_timestamp() {

        return Long.toString(System.currentTimeMillis() / 1000
        );
    }

    static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static Map<String, String> sign(String jsApiTicket, String url) {
        Map<String, String> ret = new HashMap();
        String nonceStr = create_nonce_str();
        String timestamp = create_timestamp();



        //注意这里参数名必须全部小写，且必须有序
       String  str = "jsapi_ticket=" + jsApiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" +url;

        logger.info("str:{}",str);

        String   signature = SHA1(str);

        logger.info ("signature:{}",signature);

        ret.put("url", url);
        ret.put("jsapi_ticket", jsApiTicket);
        ret.put("nonceStr", nonceStr);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1");
            digest.update(decript.getBytes("UTF-8"));
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        }
        return "";
    }
}
